package cn.itsource.crm.service.impl;

import cn.itsource.crm.domain.Contract;
import cn.itsource.crm.domain.ContractPaymentDetails;
import cn.itsource.crm.mapper.ContractPaymentDetailsMapper;
import cn.itsource.crm.service.IContractPaymentDetailsService;
import cn.itsource.crm.service.IContractService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.List;

@Service
public class ContractPaymentDetailsServiceImpl extends BaseServiceImpl<ContractPaymentDetails> implements IContractPaymentDetailsService {

    /**
     * 注入合同明细的mapper对象
     */
    @Autowired
    private ContractPaymentDetailsMapper contractPaymentDetailsMapper;

    /**
     * 注入合同的mapper对象
     */
    @Autowired
    private IContractService contractService;

    /**
     * 通过合同id查询所有合同明细
     * @param contractId
     * @return
     */
    @Override
    public List<ContractPaymentDetails> findByContractId(Long contractId) {
        return contractPaymentDetailsMapper.findByContractId(contractId);
    }

    /**
     * 通过合同id 删除所有明细
     * @param id
     */
    @Override
    public void deleteByContractId(Serializable id) {
        contractPaymentDetailsMapper.deleteByContractId(id);
    }

    /**
     * 保存明细的时候计算金额所占比例
     * @param contractPaymentDetails
     */
    @Override
    public void save(ContractPaymentDetails contractPaymentDetails) {
        //获取合同的id
        Long contractId = contractPaymentDetails.getContract().getId();

        //查询合同总金额
        Contract contract = contractService.findOne(contractId);
        BigDecimal contractSum = contract.getSum();

        //计算合同明细的金额所占的百分比---通过金额计算比例
        BigDecimal money = contractPaymentDetails.getMoney();

        BigDecimal scale = money.divide(contractSum,2,BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal("100"));

        //设置到合同明细中
        contractPaymentDetails.setScale(scale);


        //通过比例，计算金额
        //BigDecimal scale = contractPaymentDetails.getScale();
        //总金额*比例/100，得到本次付款金额,通过比例计算已付金额，感觉不合理
        //BigDecimal money = contractSum.multiply(scale).divide(new BigDecimal("100"),0,BigDecimal.ROUND_HALF_UP);
        //设置到合同明细对象中
        //contractPaymentDetails.setMoney(money);

        super.save(contractPaymentDetails);
    }
}
